import { Card } from "@/components/Card"
import { useRequest } from "ahooks"
import { Button, Form, Input, Modal, Popconfirm, Radio, Space, Table } from "antd"
import { memo, useEffect, useState } from "react"
import type { BankCard, QueryBankListParams } from "../services"
import { queryBankList, addBankList, delBankList, BankCardType } from "../services"
import type { ColumnsType } from "antd/es/table"
import { PAGINATION_CONFIG } from "@/constants"
import { enum2options } from "@/utils/enum2options"

interface BankListProps {
  orgId?: number
  name?: string
}

interface ModalProps {
  open: boolean
  title?: string
  data?: BankCard
}

const BankList: React.FC<BankListProps> = props => {
  const [params, setParams] = useState<QueryBankListParams>({
    pageNum: 1, pageSize: 10
  });
  const cardList = useRequest(() => queryBankList(params), {ready: !!params.orgId, refreshDeps: [params]})
  const addReq = useRequest(addBankList, {manual: true})
  const delReq = useRequest(delBankList, {manual: true})
  const [modalProps, setModalProps] = useState<ModalProps>({open: false})
  const [editForm] = Form.useForm()

  const openModal = (record?: BankCard) => {
    editForm.setFieldsValue(record)
    setModalProps({
      open: true, title: record ? '编辑账户' : '添加账户', data: record,
    })
  }

  const onCancel = () => {
    editForm.resetFields()
    setModalProps({open: false})
  }

  const onOk = () => {
    editForm.validateFields().then(values => {
      addReq.runAsync({
        ...modalProps.data,
        ...values,
        orgId: params.orgId,
      }).then(() => {
        cardList.refresh()
        onCancel()
      })
    })
  }

  const searchList = () => {
    setParams({...params, pageNum: 1})
  }

  const columns: ColumnsType<BankCard> = [
    {
      title: '收款户名',
      key: 'name',
      width: 160,
      render: () => props.name,
    },
    {
      title: '银行卡号',
      dataIndex: 'bankCode',
      width: 200,
    },
    {
      title: '开户行',
      dataIndex: 'bankName',
      width: 160,
    },
    {
      title: '是否默认',
      dataIndex: 'isDefault',
      width: 100,
      render: val => val === 1 ? '是' : '否'
    },
    {
      title: '账户类型',
      dataIndex: 'infoType',
      width: 120,
      render: val => BankCardType[val],
    },
    {
      title: '操作',
      key: 'operation',
      width: 120,
      render: (_, record) => {
        return <Space>
          <a onClick={() => openModal(record)}>编辑</a>
          <Popconfirm
            title={`确定删除银行卡: ${record.bankCode} 吗?`}
            onConfirm={() => delReq.runAsync({businessId: record.id, status: 3}).then(cardList.refresh)}
            okText="删除"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      }
    },
  ]

  useEffect(() => {
    if (props.orgId) {
      setParams({
        pageNum: 1, pageSize: 10, orgId: props.orgId
      })
    }
  }, [props.orgId])
  
  return (
    <Card
      header='账户信息'
      extra={<Space>
        <Button type='primary' onClick={() => searchList()} loading={cardList.loading}>查询</Button>
        <Button type='primary' onClick={() => openModal()}>添加账户</Button>
      </Space>}
    >
      <Table<BankCard>
        rowKey='id'
        loading={cardList.loading}
        dataSource={cardList.data?.data}
        columns={columns}
        pagination={{
          ...PAGINATION_CONFIG,
          current: params.pageNum,
          pageSize: params.pageSize,
          total: cardList.data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setParams({
              ...params,
              pageNum: page === params.pageNum ? 1 : page,
              pageSize,
            })
          }
        }}
      />
      <Modal
        open={modalProps.open}
        title={modalProps.title}
        onCancel={onCancel}
        onOk={onOk}
        confirmLoading={addReq.loading}
      >
        <Form form={editForm} name='bankCardForm'>
          <Form.Item name='bankCode' label='银行卡号' rules={[{required: true, message: '请输入银行卡号'}]}>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item name='bankName' label='开户行' rules={[{required: true, message: '请输入开户行'}]}>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item name='infoType' label='卡类型' rules={[{required: true, message: '请选择卡类型'}]}>
            <Radio.Group options={enum2options(BankCardType)} />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  )
}

export default memo(BankList)